<template>
	<div class="app-container own-app-container">
		<el-main>
			<el-divider content-position="left"><span class="text-lg text-bold">过滤点位</span></el-divider>
			<div class="search">
				<el-form ref="searchForm" :inline="true" :model="searchForm" class="form-inline" size="mini"
					:rules="searchRules">
					<el-row>
						<el-form-item prop="date_range">
							<el-tooltip slot="label" placement="top" content="改变时间段,将清空已分配内容">
								<span>时间段<i class="el-icon-question"></i></span>
							</el-tooltip>
							<el-date-picker :clearable="false" class="margin-xs" size="mini"
								v-model="searchForm.date_range" type="daterange" range-separator="至"
								start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy年MM月dd日"
								value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']"
								style="width:382px; margin: 0;" @change="changeDateRange">
							</el-date-picker>
						</el-form-item>
						<el-form-item label="省市">
							<el-cascader filterable v-model="searchForm.pca" clearable filterable placeholder="请选择省市"
								:options="pcAll" @change="changeCity"></el-cascader>
						</el-form-item>
						<el-form-item label="地址">
							<el-input clearable v-model="searchForm.address" placeholder="请输入搜索地址"
								style="width:382px; margin: 0;">
								<el-button slot="append" icon="el-icon-search" @click.native="searchAddress">
								</el-button>
							</el-input>
						</el-form-item>
						<el-form-item label="辐射半径" v-show="!!searchForm.address_circle.lat"
							prop="address_circle.radius">
							<el-input v-model="searchForm.address_circle.radius" type="number" :min="1">
								<template slot="append">米</template>
							</el-input>
						</el-form-item>
					</el-row>
					<el-row>
						<el-form-item label="楼盘" prop="building_area_ids">
							<el-select clearable filterable multiple v-model="searchForm.building_area_ids"
								placeholder="请选择楼盘">
								<el-option v-for="item in buildingAreaList" :key="item.id" :label="item.name"
									:value="item.id">
									<span style="float: left">{{ item.name }}</span>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="投放行业" prop="industry_id">
							<el-col :span="24">
								<el-select clearable filterable v-model="searchForm.industry_id" placeholder="选择投放行业"
									style="width:100%">
									<el-option v-for="item in industryList" :key="item.id" :label="item.name"
										:value="item.id" :disabled="!item.status || !!item.deleted_at">
										<span style="float: left">{{ item.name }}</span>
										<span
											:style="{float:'right',color:(!!item.deleted_at?'#e54d42':(!item.status?'#8492a6':'')),fontSize:'12px'}">
											{{!!item.deleted_at?'已删除':(!item.status?'已禁用':'')}}</span>
									</el-option>
								</el-select>
							</el-col>
						</el-form-item>
						<el-form-item label="均价下限" prop="price_range.min">
							<el-col :span="24">
								<el-input v-model="searchForm.price_range.min" type="number" :min="1">
									<template slot="append">元</template>
								</el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="均价上限" prop="price_range.max">
							<el-col :span="24">
								<el-input v-model="searchForm.price_range.max" type="number" :min="1">
									<template slot="append">元</template>
								</el-input>
							</el-col>
						</el-form-item>
					</el-row>
					<el-row>
						<el-form-item label="点位类型" prop="point_type_ids" v-show="(point_types || []).length > 1">
							<el-select clearable filterable multiple :multiple-limit="1"
								v-model="searchForm.point_type_ids" placeholder="选择点位类型" @change="changePointType">
								<el-option v-for="item in point_types" :key="item.id" :label="item.name"
									:value="item.id">
									<span style="float: left">{{ item.name }}</span>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="行政区划" prop="adcodes">
							<el-select clearable filterable multiple v-model="searchForm.adcodes" placeholder="请选择行政区划">
								<el-option v-for="item in areaAll" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
						<el-form-item label="商圈">
							<el-select clearable filterable v-model="trade_area_selected" placeholder="请选择商圈"
								size="mini" @change="changeTradeAreaSelect" value-key="id">
								<el-option v-for="item in tradeAreaAll" :key="item.id" :label="item.title"
									:value="item">
									<div class="flex justify-between align-center flex-no-wrap">
										<div class="text-df">{{item.title}}</div>
										<div class="text-xs text-gray margin-left">{{item.address}}</div>
									</div>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="商圈辐射半径" prop="business_circle.radius">
							<el-input v-model="searchForm.business_circle.radius" type="number" :min="1">
								<template slot="append">米</template>
							</el-input>
						</el-form-item>
						<el-form-item style="margin-left: 30px;">
							<el-button type="primary" plain @click="searchSubmit('searchForm')">获取待选楼盘</el-button>
							<el-button type="info" plain @click="searchReset">重置</el-button>
						</el-form-item>
					</el-row>

				</el-form>
			</div>
			<el-divider content-position="left" v-if="(pointRule.rules || []).length > 0"><span
					class="text-lg text-bold">点位分配规则</span></el-divider>
			<div class="flex justify-start align-center flex-wrap text-sm" style="width: 100%"
				v-show="(pointRule.rules || []).length > 0" v-loading="loadingRules">
				<el-card shadow="never" style="line-height: 28px;" class="margin-lr-xs" v-for="rule in pointRule.rules"
					:key="rule.id">
					<template v-if="rule.id==1||rule.id==2">
						<el-switch v-model="rule.on" size="mini" class="margin-right-xs"
							@change="(val) => changRuleSwitch(val, rule.id)" />{{rule.name}}
						<el-input-number v-model="rule.n" :controls="false" size="mini" :min="1" step-strictly
							class="margin-left-xs" @change="changRuleN" /> 个
					</template><template v-else-if="rule.id==3">
						<el-switch v-model="rule.on" size="mini" class="margin-right-xs"
							@change="(val) => changRuleSwitch(val, rule.id)" /> {{rule.name}}1个
					</template><template v-else-if="rule.id==4||rule.id==5||rule.id==6">
						<el-switch v-model="rule.on" size="mini" class="margin-right-xs"
							@change="(val) => changRuleSwitch(val, rule.id)" />{{rule.name}}
					</template><template v-else-if="rule.id==7">
						<el-select clearable filterable multiple v-model="rule.appoint" size="mini" placeholder="限定楼层"
							style="width:100%" @change="(val) => changeRuleAppoint(val, rule.id)">
							<el-option v-for="item in floorList" :key="item" :label="item" :value="item" />
						</el-select>
					</template>
				</el-card>
				<div class="margin-left text-red" style="width:300px;line-height: 1.5;">
					注：应用规则时，请尽量精准选点，否则可能会由于工人实际上刊，产生规则内数量不足的情况。</div>
			</div>
			<el-divider content-position="left"><span class="text-lg text-bold">选取点位</span></el-divider>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-divider content-position="left"><span class="text-df text-bold">待选楼盘</span></el-divider>
					<el-table stripe ref="multipleTable" :data="tableData" tooltip-effect="dark" v-loading="tabLoading"
						style="width: 100%" border highlight-current-row row-key="id" size="mini">
						<el-table-column type="index" label="序号" width="50" fixed="left">
							<template slot-scope="scope">
								<span>{{ scope.$index + 1 }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="name" min-width="100" label="楼盘" fixed="left">
						</el-table-column>
						<el-table-column label="具体点位" width="90" align="center">
							<template slot-scope="scope">
								<el-button class="text-underline" type="text" size="mini"
									@click.native="showExactList((scope.row.devices[searchForm.point_type_ids[0]] || []))">
									{{(scope.row.devices[searchForm.point_type_ids[0]] || []).length}}
								</el-button>
							</template>
						</el-table-column>
						<el-table-column prop="cur_can_count" label="可分配数" width="90" align="center">
						</el-table-column>
						<el-table-column prop="all_count" label="总数" width="90" align="center">
						</el-table-column>
						<el-table-column prop="can_count" label="空闲" width="90" align="center">
							<template slot-scope="scope">
								<span class="text-green">{{scope.row.can_count || 0}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="lock_count" label="锁定" width="90" align="center">
							<template slot-scope="scope">
								<span class="text-orange">{{scope.row.lock_count || 0}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="used_count" label="上刊" width="90" align="center">
							<template slot-scope="scope">
								<span class="text-red">{{scope.row.used_count || 0}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="court_count" label="总安装" width="90" align="center"
							v-if="tableColShow.hasCourt">
						</el-table-column>
						<el-table-column prop="unit_count" label="单元数" width="90" align="center"
							v-if="tableColShow.hasUnit">
						</el-table-column>
						<el-table-column prop="floor_count" label="楼层数" width="90" align="center"
							v-if="tableColShow.hasFloor">
						</el-table-column>
						<el-table-column prop="a_count" label="A面数" width="90" align="center" v-if="tableColShow.hasA">
						</el-table-column>
						<el-table-column prop="b_count" label="B面数" width="90" align="center" v-if="tableColShow.hasB">
						</el-table-column>
						<el-table-column prop="ab_count" label="A面+B面数" width="90" align="center"
							v-if="tableColShow.hasAB">
						</el-table-column>
						<el-table-column prop="area" min-width="100" label="区" show-overflow-tooltip></el-table-column>
						<el-table-column prop="province" min-width="100" label="省" show-overflow-tooltip>
						</el-table-column>
						<el-table-column prop="city" min-width="100" label="市" show-overflow-tooltip></el-table-column>
						<el-table-column prop="price" min-width="100" label="均价(元)" show-overflow-tooltip>
						</el-table-column>
						<el-table-column label="操作" width="120px" align="center" fixed="right">
							<template slot-scope="scope">
								<el-button-group>
									<el-button icon="el-icon-circle-plus-outline" size="mini" type="primary"
										@click.native="chooseBuilding(scope.row)">选中</el-button>
								</el-button-group>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
				<el-col :span="12">
					<el-divider content-position="left"><span class="text-df text-bold">选中楼盘</span></el-divider>
					<el-form ref="distForm" inline :model="distForm" class="form-inline" size="mini">
						<el-row>
							<el-form-item label="分配总数" prop="all">
								<el-input v-model="distForm.all" type="number" :min="0" @change="changeDistAll"
									style="width:150px">
									<template slot="append">个</template>
								</el-input>
							</el-form-item>
							<el-form-item label="未分配数" prop="remain" v-show="(distForm.remain || 0) != 0">
								<span class="text-red text-bold">{{distForm.remain}}个</span>
							</el-form-item>
						</el-row>
						<el-row>
							<el-form-item label="分配方式" prop="dist_type">
								<el-radio-group v-model="distForm.dist_type">
									<el-radio :label="1">平均分配</el-radio>
									<el-radio :label="2" disabled>顺序优先</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-row>
					</el-form>

					<el-table stripe ref="multipleTableChoosed" :data="tableDataChoosed" tooltip-effect="dark"
						v-loading="tabLoadingChoosed" style="width: 100%" border highlight-current-row row-key="key"
						size="mini" show-summary :summary-method="getChoosedSummaries">
						<el-table-column type="index" label="序号" width="50" fixed="left">
							<template slot-scope="scope">
								<span>{{ scope.$index + 1 }}</span>
							</template>
						</el-table-column>
						<el-table-column min-width="130" label="应用规则" fixed="left" align="center">
							<template slot-scope="scope">
								<div class="flex flex-direction justify-start align-center">
									<el-tag v-for="(r,i) in scope.row.rules" :key="r.id" type="primary" size="mini"
										class="margin-lr-xs margin-tb-xxs" disable-transitions effect="plain">{{r.desp}}
									</el-tag>
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="name" min-width="100" label="楼盘" fixed="left">
						</el-table-column>
						<el-table-column prop="area" min-width="70" label="地区">
						</el-table-column>
						<el-table-column min-width="100" label="类型" align="center">
							<template slot-scope="scope">
								<el-tag type="success" size="mini" class="margin-lr-xs margin-tb-xxs"
									disable-transitions effect="plain">{{scope.row.point_type.name}}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column width="70" label="总空闲" align="center">
							<template slot-scope="scope">
								<span class="text-green">{{scope.row.can_count || 0}}</span>
							</template>
						</el-table-column>
						<el-table-column width="100" label="规则内可分配" prop="can" align="center">
						</el-table-column>
						<el-table-column width="90" align="center">
							<el-tooltip slot="header" placement="top" content='超出"规则内可分配"的部分,将不可用'>
								<span>分配数量<i class="el-icon-question"></i></span>
							</el-tooltip>
							<template slot-scope="scope">
								<el-input-number v-model="scope.row.to" :controls="false" size="mini"
									:min="(scope.row.to_exact || []).length" step-strictly
									:step="(scope.row.rules.filter(r => r.id==6) || []).length==1 && scope.row.to<=scope.row.can?2:1"
									style="width:100%" @change="changeChoosedTo" />
							</template>
						</el-table-column>
						<el-table-column width="70" label="精准选点" align="center">
							<template slot-scope="scope">
								<el-button class="text-underline" type="text" size="mini"
									@click.native="onExact(scope.row, scope.$index)">
									{{(scope.row.to_exact || []).length}}
								</el-button>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="120" align="center" fixed="right">
							<template slot-scope="scope">
								<el-button-group>
									<el-button icon="el-icon-delete" size="mini" type="danger"
										@click.native="delChoosed(scope.$index)">删除</el-button>
								</el-button-group>
							</template>
						</el-table-column>
					</el-table>
					<div class="flex justify-center align-center margin-top">
						<el-button type="primary" @click.native="onConfirm">确 定</el-button>
					</div>
				</el-col>
			</el-row>
		</el-main>

		<!-- 地址搜索结果弹框 -->
		<el-dialog title="相似地址" :visible.sync="addressSearchDialogVisible" width="60%" center
			@close="dialogCUClose('addressSearchDialog')">
			<div class="flex-direction justify-start align-center search-dialog">
				<div v-for="item in searchAddresses" :key="item.id"
					class="search-ad-item flex justify-between align-center padding-xs">
					<div>
						<div class="text-black text-bold">
							{{item.title}}
						</div>
						<div class="text-gray text-xs margin-top-xs">
							{{item.address}}
						</div>
					</div>
					<div class="flex justify-end align-center">
						<el-button type="text" class="padding-0 text-xs"
							@click.natvice="showAddressCircleRadius(item.location)">选择地址</el-button>
					</div>
				</div>
			</div>
		</el-dialog>
		<!-- 地址搜索结果辐射半径弹框 -->
		<el-dialog :close-on-click-modal="false" title="辐射半径" center :visible.sync="addressSearchRadiusDialogVisible"
			width="40%" @close="dialogCUClose('radiusForm')">
			<el-form ref="addressSearchRadiusForm" :model="searchForm" label-width="100px" center>
				<el-row class="margin-top-sm">
					<el-col :span="24">
						<el-form-item label="辐射半径" prop="address_circle.radius">
							<el-col :span="24">
								<el-input clearable v-model.trim="searchForm.address_circle.radius" type="number"
									placeholder="请输入辐射半径">
									<template slot="append">米</template>
								</el-input>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click.native="addressSearchRadiusDialogVisible=false">取 消</el-button>
				<el-button type="primary" @click.native="confirmAddressSearchRadius()">确 定</el-button>
			</span>
		</el-dialog>

		<el-dialog :close-on-click-modal="false" append-to-body title="具体点位" center :visible.sync="exactVisible"
			width="70%" @closed="dialogCUClose('exactTable')">
			<el-table ref="exactTable" :data="exactList" stripe size="mini" tooltip-effect="dark" style="width: 100%;"
				max-height="400" border highlight-current-row row-key="id">
				<el-table-column type="index" width="50" />
				<el-table-column label="编号" width="120" prop="code" sortable />
				<el-table-column label="详情" min-width="200" prop="address"></el-table-column>
				<el-table-column label="特点" width="120" prop="media_feature" sortable />
			</el-table>
			<div class="margin-tb-xs text-sm">共计<span class="text-green">{{(exactList || []).length || 0}}</span>个</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click.native="exactVisible=false;dialogCUClose('exactTable')">关 闭</el-button>
			</span>
		</el-dialog>

		<!-- <exact-table :exactVisible.sync="exactVisible2" :useRequestData="exactuseRequestData"
			:buildingId="exactBuildingAreaId" :pointTypeId="exactPointTypeId" :dateRange="exactDateRange"
			:toExact="exactToExact" :treeData="exactToExactTreeData" :can="exactCan" :total="exactTotal"
			:key="exactTimer" @choosed="choosedToExact" /> -->
			
		<exact-view :exactVisible.sync="exactVisible2" :toExact="exactToExact" :viewData="exactToExactViewData" :can="exactCan" :total="exactTotal"
			:key="exactTimer" @choosed="choosedToExact" />
	</div>
</template>

<script>
	import common from '@/utils/common.js';
	import {
		Message
	} from 'element-ui'
	import {
		cloneDeep
	} from 'lodash'
	import {
		isArray,
		isObject,
		isTrue,
		isFunction,
		generateUUID,
		accMul,
		accAdd,
		formatDate,
		getTimeSlot,
		getAdcodeListByAdcode,
		compareArrayToGetDiffs
	} from '@/utils/util.js'
	import {
		list_all3rd_bycode,
		list_all3rd_bytopcode,
		list_all3rd_bycode_contrain_del_close,
		list_all3rd_bytopcode_contrain_del_close
	} from '@/api/business/setting/dict'
	import {
		area_list, // 根据市id获取所有区
		search_trade_area, // 商圈
		pc_list_all, // 所有省市
		search_address, //腾讯位置服务，地址搜索
		get_all_list as get_buildings
	} from '@/api/business/building/building.js'
	import {
		get_company_adcode,
		get_point_type_dis_rule,
		get_choose_data,
		get_company_floors
	} from '@/api/business/building/choose_point.js'

	import ExactTable from '@/components/TencentMap/ExactTable'
	import ExactView from '@/components/TencentMap/ExactView'

	export default {
		name: 'choosePointByList',
		// beforeRouteLeave(to, from, next) {
		// 	this.$destroy();
		// 	next();
		// },
		components: {
			ExactTable,
			ExactView
		},
		data() {
			return {

				point_types: [],
				point_types_map: new Map(),
				buildingAreaList: [],
				tradeAreaAll: [],
				// 当前选中市下的所有区
				areaAll: [],
				industryList: [],

				pointRule: {
					rules: []
				},
				pointRuleMap: {},
				loadingRules: false,

				trade_area_selected: {},
				// search form
				searchForm: {
					point_type_ids: [],
					date_range: [formatDate(new Date()) + ' 00:00:00', formatDate(new Date()) + ' 23:59:59'],
					building_area_ids: [],
					pca: null,
					address: null,
					address_circle: {
						lng: null,
						lat: null,
						radius: 1000
					},
					business_circle: {
						lat: null,
						lng: null,
						radius: 1000
					},
					industry_id: null,
					price_range: {
						min: null,
						max: null
					}
				},
				searchRules: {
					point_type_ids: [{
						required: true,
						message: '请选择一种点位类型',
						trigger: 'change'
					}]
				},
				// list table
				listParams: {
					point_type_ids: [],
					date_range: [],
					building_area_ids: [],
					pca: null,
					address: null,
					address_circle: {
						lng: null,
						lat: null,
						radius: 1000
					},
					business_circle: {
						lat: null,
						lng: null,
						radius: 1000
					},
					industry_id: null,
					price_range: {
						min: null,
						max: null
					}
				}, // list参数
				tabLoading: false,
				tableColShow: {
					hasCourt: false,
					hasUnit: false,
					hasFloor: false,
					hasA: false,
					hasB: false,
					hasAB: false,
				},
				activeRule: [],
				tableData: [],
				tableDataOrigin: [],


				tableDataChoosed: [],
				tabLoadingChoosed: false,
				tableDataChoosedSum: {
					to: 0, // 分配数
					can: 0, // 规则下可分配数
					can_count: 0, // 总空闲数
					to_exact: 0, // 精准选点数
				},

				floorList: [],


				exactVisible: false,
				exactList: [],

				exactVisible2: false,
				exactuseRequestData: true,
				exactBuildingAreaId: '',
				exactPointTypeId: '',
				exactDateRange: ['', ''],
				exactToExact: [],
				exactToExactTreeData: [],
				exactToExactViewData: [],
				exactTotal: 0,
				exactCan: 0,
				exactTimer: '',

				pcAll: [],
				addressSearchDialogVisible: false,
				searchAddresses: [],
				addressSearchRadiusDialogVisible: false,

				distForm: {
					all: 0,
					dist_type: 1,
					remain: 0
				}
			}
		},
		computed: {

		},
		created() {
			this.$nextTick(() => {
				this.$refs.searchForm.clearValidate();
			})
		},
		mounted() {
			this.resetDateRangeByQuery()
			this.getPointTypes()
			this.getAllBuildings()
			this.getCompanyAdcode()
			this.getIndustryList()
			this.getCompanyFloors()
		},
		methods: {
			// 检查分配数量大于可用数的，进行二次确认
			checkNum() {
				const that = this
				return new Promise(async (resolve, reject) => {
					let flag = true,
						to_sum = 0;
					(that.tableDataChoosed || []).forEach(b => {
						if (b.to > b.can) flag = false;
						to_sum += b.to;
					});
					if (!flag) {
						const confirm = await common.confirmDialog('存在“分配数”超出“规则可分配数”，超出部分不可用，为无效数据，您确认吗？')
						resolve(confirm)
					} else if (to_sum == 0) {
						await common.messageError('未分配任何点位！')
						resolve(false)
					} else {
						resolve(true)
					}
				})
			},
			// 确定
			async onConfirm() {
				const that = this
				if ((that.distForm.remain || 0) != 0) {
					common.messageError('请检查剩余数，未分配完全！')
					return false
				}
				const confirm = await that.checkNum()
				if (confirm) {
					common.savePageData(that.generateSettingInfo(), 'MapPointDistSetting');
					that.$emit('on-confirm');
				}
			},
			generateSettingInfo() {
				const that = this
				let returnData = {
					building_areas: [],
					point_types: [],
					to: {},
					to_exact: {},
					uuid: {},
					date_range: that.searchForm.date_range,
					one_limit: {},
					floor_limit: {},
					rules: {},
					show_rules: false
				}

				let showRules = false;
				let bSet = new Set(),
					pSet = new Set();
				(that.tableDataChoosed || []).forEach(b => {
					const bId = b.id;
					const pId = b.point_type.id;
					const key = bId + '_' + pId;
					returnData.one_limit['' + pId] = false;
					returnData.floor_limit['' + pId] = 1;
					returnData.uuid[key] = generateUUID();
					if (!bSet.has(bId)) {
						returnData.building_areas.push({
							id: bId,
							name: b.name
						});
						bSet.add(bId);
					}
					if (!pSet.has(pId)) {
						returnData.point_types.push({
							id: pId,
							name: b.point_type.name
						});
						pSet.add(pId);
					}
					returnData.rules[key] = b.rules;
					showRules = showRules || (b.rules || []).length > 0;
					returnData.to[key] = b.to;
					returnData.to_exact[key] = (b.to_exact || []).map(ex => {
						if (!ex.obj) {
							return ex;
						} else {
							return Object.assign(ex.obj, {
								media_type_id: ex.obj.point_type_id,
								media_type_pid: ex.obj.point_type_pid,
								media_type: b.point_type.name
							});
						}
					}) || [];
				});
				returnData.show_rules = showRules;

				return returnData;
			},
			// 改变分配总数
			changeDistAll() {
				const that = this;
				that.distAll();
			},
			// 分配点位
			distAll() {
				const that = this;
				if (that.distForm.dist_type == 1) {
					that.equalDist();
				} else if (that.distForm.dist_type == 2) {
					// todo 顺序优先
				}
			},
			// 平均分配
			equalDist() {
				const that = this;
				let all = that.distForm.all || 0;
				let remain = parseInt(all);
				let list = JSON.parse(JSON.stringify(that.tableDataChoosed || []));
				list.forEach(d => {
					d.to = 0;
				});

				// 优先分配规则内的
				let flag = false;
				while (remain > 0 && !flag) {
					flag = true;
					list.forEach(d => {
						if (d.can > d.to && remain > 0) {
							d.to++;
							remain--;
							flag = flag && false;
						}
					})
				}
				// 后分配规则外的
				let flag1 = false;
				while (remain > 0 && !flag1) {
					flag1 = true;
					list.forEach(d => {
						if (d.can_count > d.to && remain > 0) {
							d.to++;
							remain--;
							flag1 = flag1 && false;
						}
					})
				}

				that.distForm.remain = remain || 0;
				that.tableDataChoosed = JSON.parse(JSON.stringify(list || []));
				that.calChoosedSum();
			},
			// 精准选点
			onExact(row, index) {
				const that = this;
				that.exactRowIndex = index;
				that.exactuseRequestData = (row.rules || []).length <= 0;
				that.exactBuildingAreaId = '' + row.id;
				that.exactPointTypeId = '' + row.point_type.id;
				that.exactDateRange = that.searchForm.date_range || ['', ''];
				that.exactToExact = row.to_exact || [];
				// if (!that.exactuseRequestData) {
				// 	const {
				// 		list,
				// 		count
				// 	} = that.getRuleExactTreeData(row.can_devices);
				// 	that.exactToExactTreeData = list;
				// 	that.exactTotal = count;
				// }
				
				// 使用图形化选点页
				const {
					list,
					count
				} = that.getExactViewData(row.can_devices, row.devices, that.exactuseRequestData || false);
				that.exactToExactViewData = list;
				that.exactTotal = count;
				that.exactCan = row.can || 0;
				that.exactVisible2 = true;
				
				// that.$nextTick(() => {
				// 	that.exactTimer = new Date().getTime();
				// })
			},
			// 生成块形具体点位选点数据
			/**
			 * @param can_devices
			 * @param devices
			 * @param flag
			 */
			getExactViewData(can_devices, all_devices, flag) {
				const that = this;
				let list = [],
					count = 0;
				let devices = [];
				if (flag) {
					devices = all_devices[that.searchForm.point_type_ids[0]] || [];
					const len = (devices || []).length;
					if (len > 0) {
						const m_id = devices[0].point_type_id;
						const m_pid = devices[0].point_type_pid;
						let dMap = new Map();
						devices.forEach(d => {
							let item = {
								id: d.id,
								level: 4,
								name: d.address,
								isLeaf: true,
								obj: d
							};
							if (m_pid == 119) {
								let build = dMap.get('' + d.building_number) || {
									id: generateUUID(),
									name: d.building_number + '号楼',
									level: 1,
									isLeaf: false,
									isLastP: false,
									list: [],
									map: new Map()
								};
								let unit = build.map.get('' + d.unit_number) || {
									id: generateUUID(),
									name: d.unit_number + '单元',
									level: 2,
									isLeaf: false,
									isLastP: false,
									list: [],
									map: new Map()
								};
								let floor = unit.map.get('' + d.floor) || {
									id: generateUUID(),
									name: d.floor + '层',
									level: 3,
									isLeaf: false,
									isLastP: true,
									list: []
								};
								floor.list.push(item);
								unit.map.set('' + d.floor, floor);
								build.map.set('' + d.unit_number, unit);
								dMap.set('' + d.building_number, build);
							}
							if (m_pid == 120) {
								if (m_id == 135) {
									item.level = 3;
									let door = dMap.get('' + d.door_number) || {
										id: generateUUID(),
										name: d.door_number + '号门',
										level: 1,
										isLeaf: false,
										isLastP: false,
										list: [],
										map: new Map()
									};
									let rail = door.map.get('' + d.rail_number) || {
										id: generateUUID(),
										name: d.rail_number + '号护栏',
										level: 2,
										isLeaf: false,
										isLastP: true,
										list: []
									};
									rail.list.push(item);
									door.map.set('' + d.rail_number, rail);
									dMap.set('' + d.door_number, door);
								} else {
									item.level = 2;
									let door = dMap.get('' + d.door_number) || {
										id: generateUUID(),
										name: d.door_number + '号门',
										level: 1,
										isLeaf: false,
										isLastP: true,
										list: []
									};
									door.list.push(item);
									dMap.set('' + d.door_number, door);
								}
							}

							if (m_pid == 130) {
								item.level = 2;
								list.push(item);
								count++;
							}
						});
						
						console.log(dMap);
						if (dMap.size > 0) {
							dMap.forEach((v1, k1) => {
								let first = {
									id: v1.id,
									name: v1.name,
									level: v1.level,
									isLeaf: v1.isLeaf,
									list: v1.list
								}
								if (!v1.isLeaf) {
									if(!v1.isLastP){
										v1.map.forEach((v2, k2) => {
											let second = {
												id: v2.id,
												name: v2.name,
												level: v2.level,
												isLeaf: v2.isLeaf,
												list: v2.list
											}
											if (!v2.isLeaf) {
												if(!v2.isLastP){
													v2.map.forEach((v3, k3) => {
														let third = {
															id: v3.id,
															name: v3.name,
															level: v3.level,
															isLeaf: v3.isLeaf,
															list: v3.list
														}
														count += (third.list || []).length;
														second.list.push(third);
													});
												}else{
													count += (second.list || []).length;
												}
											}
											first.list.push(second);
										});
									}else{
										count += (first.list || []).length;
									}
								}
								list.push(first);
							});
						}
					}
				} else {
					devices = can_devices;
					if (devices.type == 0) {
						devices.list.forEach(d => {
							if (!!d.a && !!d.b) { //A面+B面打包
								list.push({
									id: d.a.id + '_' + d.b.id,
									name: d.a.address + '+B面',
									isLeaf: false,
									level: 1,
									ruleId: 6,
									list: [{
											id: d.a.id,
											level: 2,
											name: d.a.address,
											isLeaf: true,
											obj: d.a
										},
										{
											id: d.b.id,
											level: 2,
											name: d.b.address,
											isLeaf: true,
											obj: d.b
										}
									]
								});
								count += 2;
							} else {
								list.push({
									id: d.id,
									level: 1,
									name: d.address,
									isLeaf: true,
									obj: d
								});
								count++;
							}
						});
					} else if (devices.type == 1) {
						const keys = Object.keys(devices.split || {}) || [];
						keys.forEach(key => {
							const nums = key.split('_');
							let building_num = '',
								unit_num = '',
								floor_num = '';
							if (nums.length >= 2) {
								building_num = nums[0];
								unit_num = nums[1];
							}
							if (nums.length >= 3) {
								floor_num = nums[2];
							}
							const id = ['p', ...(devices.split[key].list || []).map(d => d.id)].join('_');
							const name = building_num + '号楼' + unit_num + '单元' + (floor_num ? (floor_num + '层') :
								'');
							const deviceList = devices.split[key].list.map(d => {
								return {
									id: d.id,
									name: d.address,
									level: 2,
									isLeaf: true,
									obj: d
								};
							}) || [];
							list.push({
								id: id,
								name: name,
								level: 1,
								isLeaf: false,
								max: devices.split[key].max,
								list: deviceList
							});
							count += deviceList.length;
						});
					} else if (devices.type == 2) {
						const keys = Object.keys(devices.split || {}) || [];
						keys.forEach(key => {
							const nums = key.split('_');
							let building_num = '',
								unit_num = '';
							if (nums.length >= 2) {
								building_num = nums[0];
								unit_num = nums[1];
							}
							const id = ['p', ...(devices.split[key].list || []).map(inner => {
								return (inner.list || []).map(d => d.id).join('_');
							})].join('_');
							const name = building_num + '号楼' + unit_num + '单元';
							let dCount = 0;
							const innerList = (devices.split[key].list || []).map(inner => {
								const innerId = ['i', ...(inner.list || []).map(d => d.id)].join('_');
								const innerName = inner.floor + '层';
								const deviceList = (inner.list || []).map(d => {
									dCount++;
									return {
										id: d.id,
										level: 3,
										name: d.address,
										isLeaf: true,
										obj: d
									};
								}) || [];
								return {
									id: innerId,
									level: 2,
									name: innerName,
									isLeaf: false,
									max: inner.max,
									list: deviceList
								}
							}) || [];
							let innerLength = 0;
							innerList.forEach(i => {
								innerLength += i.list.length;
							});
							list.push({
								id: id,
								level: 1,
								name: name,
								isLeaf: false,
								max: devices.split[key].max,
								list: innerList
							});
							count += dCount;
						});
					}
					//console.log('list2', JSON.parse(JSON.stringify(list)));
				}
				//console.log('list3', JSON.parse(JSON.stringify(list)));
				return {
					list,
					count
				}
			},
			// 根据规则组合具体点位，树形
			getRuleExactTreeData(devices) {
				const that = this;
				let list = [],
					count = 0;
				if (devices.type == 0) {
					devices.list.forEach(d => {
						if (!!d.a && !!d.b) { //A面+B面打包
							list.push({
								id: d.a.id + '_' + d.b.id,
								name: d.a.address + '+B面',
								isLeaf: false,
								type: 0,
								ruleId: 6,
								list: [{
										id: d.a.id,
										type: 0,
										name: d.a.address,
										isLeaf: true,
										obj: d.a
									},
									{
										id: d.b.id,
										type: 0,
										name: d.b.address,
										isLeaf: true,
										obj: d.b
									}
								]
							});
							count += 2;
						} else {
							list.push({
								id: d.id,
								type: 0,
								name: d.address,
								isLeaf: true,
								obj: d
							});
							count++;
						}
					});
				} else if (devices.type == 1) {
					const keys = Object.keys(devices.split || {}) || [];
					keys.forEach(key => {
						const nums = key.split('_');
						let building_num = '',
							unit_num = '',
							floor_num = '';
						if (nums.length >= 2) {
							building_num = nums[0];
							unit_num = nums[1];
						}
						if (nums.length >= 3) {
							floor_num = nums[2];
						}
						const id = ['p', ...(devices.split[key].list || []).map(d => d.id)].join('_');
						const name = building_num + '号楼' + unit_num + '单元' + (floor_num ? (floor_num + '层') : '');
						const deviceList = devices.split[key].list.map(d => {
							return {
								id: d.id,
								type: 1,
								pid: id,
								name: d.address,
								isLeaf: true,
								obj: d
							};
						}) || [];
						list.push({
							id: id,
							type: 1,
							name: name,
							isLeaf: false,
							max: devices.split[key].max,
							disabled: devices.split[key].max < deviceList.length,
							list: deviceList
						});
						count += deviceList.length;
					});
				} else if (devices.type == 2) {
					const keys = Object.keys(devices.split || {}) || [];
					keys.forEach(key => {
						const nums = key.split('_');
						let building_num = '',
							unit_num = '';
						if (nums.length >= 2) {
							building_num = nums[0];
							unit_num = nums[1];
						}
						const id = ['p', ...(devices.split[key].list || []).map(inner => {
							return (inner.list || []).map(d => d.id).join('_');
						})].join('_');
						const name = building_num + '号楼' + unit_num + '单元';
						let dCount = 0;
						const innerList = (devices.split[key].list || []).map(inner => {
							const innerId = ['i', ...(inner.list || []).map(d => d.id)].join('_');
							const innerName = inner.floor + '层';
							const deviceList = (inner.list || []).map(d => {
								dCount++;
								return {
									id: d.id,
									type: 2,
									pid: innerId,
									rid: id,
									level: 3,
									name: d.address,
									isLeaf: true,
									obj: d
								};
							}) || [];
							return {
								id: innerId,
								type: 2,
								pid: id,
								rid: id,
								level: 2,
								name: innerName,
								isLeaf: false,
								max: inner.max,
								disabled: inner.max < deviceList.length,
								list: deviceList
							}
						}) || [];
						let innerLength = 0;
						innerList.forEach(i => {
							innerLength += i.list.length;
						});
						list.push({
							id: id,
							type: 2,
							pid: 0,
							rid: id,
							level: 1,
							name: name,
							isLeaf: false,
							max: devices.split[key].max,
							disabled: devices.split[key].max < innerLength,
							list: innerList
						});
						count += dCount;
					});
				}
				return {
					list,
					count
				};
			},
			// 精准选点结果
			choosedToExact(val) {
				const that = this;
				that.tableDataChoosed[parseInt(that.exactRowIndex)].to_exact = JSON.parse(JSON.stringify(val || []));
				const toExactCount = that.tableDataChoosed[parseInt(that.exactRowIndex)].to_exact.length;
				if (toExactCount > that.tableDataChoosed[parseInt(that.exactRowIndex)].to) that.tableDataChoosed[parseInt(
					that.exactRowIndex)].to = toExactCount;
				that.calChoosedSum();
			},
			// 改变时间段
			changeDateRange() {
				const that = this;
				that.tableDataChoosed = [];
				that.calChoosedSum();
				that.tableDataOrigin = [];
				that.getCurActiveRule();
				that.filterTableData();
			},
			// 改变分配数
			changeChoosedTo() {
				const that = this;
				that.$nextTick(() => {
					that.calChoosedSum();
				});
			},
			// 获取公司所有楼层
			getCompanyFloors() {
				const that = this;
				get_company_floors()
					.then(({
						data
					}) => {
						that.floorList = data;
					});
			},
			// 查询地址
			async searchAddress() {
				const that = this

				if (!that.searchForm.pca || that.searchForm.pca.length == 0) {
					common.message({
						message: '请选择省市',
						type: 'error'
					})
					return false
				}
				if (!that.searchForm.address) {
					common.message({
						message: '请输入地址',
						type: 'error'
					})
					return false
				}
				const loading = common.showLoading({
					text: '搜索中'
				})
				let search_data = {
					keyword: that.searchForm.address,
					boundary: that.searchForm.pca[that.searchForm.pca.length - 1]
				}
				/* if(that.hasInfoAdd){
					search_data.category = '房产小区'
				} */
				search_address(search_data)
					.then(res => {
						const {
							code,
							data: {
								data
							}
						} = res
						if (code == 200) {
							loading.close()
							that.searchAddresses = data
							that.addressSearchDialogVisible = true
						}
					})
					.catch(() => {
						loading.close()
					})
			},
			// 改变省市
			changeCity(val) {
				const that = this
				const code = val[val.length - 1]
				that.getAreaList(code).then(() => {
					that.searchForm.adcodes = [];
				});
			},
			// 获取所有省市
			getPCListAll() {
				const that = this
				return new Promise((resolve, reject) => {
					pc_list_all()
						.then(res => {
							const {
								code,
								data
							} = res
							if (code == 200) {
								if (data && data.length > 0) {
									that.pcAll = data
									resolve()
								}
							}
						})
				})

			},
			// 显示地址辐射半径填写框
			showAddressCircleRadius({
				lat,
				lng
			}) {
				const that = this;
				that.searchForm.address_circle.lat = lat;
				that.searchForm.address_circle.lng = lng;
				that.addressSearchDialogVisible = false;
				that.addressSearchRadiusDialogVisible = true;
			},
			// 确认地址辐射半径
			confirmAddressSearchRadius() {
				const that = this;
				that.addressSearchRadiusDialogVisible = false;
			},
			// 删除已选中楼盘
			async delChoosed(index) {
				const that = this;
				const confirm = await common.confirmDialog('您确定要删除?');
				if (confirm) {
					that.tableDataChoosed.splice(index, 1);
					that.distAll();
				}
			},
			// 选择楼盘
			chooseBuilding(row) {
				const that = this;
				that.tabLoadingChoosed = true;
				that.getCurActiveRule();
				let rules = [];
				(that.pointRule.rules || []).forEach(r => {
					if (that.activeRule.indexOf(r.id) > -1) {
						let rule = Object.assign({
							desp: r.name + ((r.id == 1 || r.id == 2 || r.id == 3) ? (r.n + '个') :
								((r.id == 7) ? ('(' + r.appoint.join(',') + ')') : ''))
						}, r);
						rules.push(rule);
					}
				});
				that.tableDataChoosed = that.tableDataChoosed || [];
				const choosed = that.tableDataChoosed.filter(b => b.id == row.id && b.point_type.id == that.searchForm
					.point_type_ids[0]); // 该楼盘是否已选中
				if ((choosed || []).length > 0) {
					common.messageError('该楼盘的该点位类型已经选中，请前往分配!');
				} else {
					that.tableDataChoosed.push({
						id: row.id,
						key: row.id + '_' + that.searchForm.point_type_ids[0],
						adcode: row.adcode,
						area: row.area,
						name: row.name,
						point_type: cloneDeep(that.point_types_map.get(that.searchForm.point_type_ids[0])),
						to: 0,
						can: row.cur_can_count,
						can_devices: row.cur_can_devices,
						can_count: row.can_count,
						rules: rules,
						to_exact: [],
						devices: row.devices
					});
					that.calChoosedSum();
				}

				that.tabLoadingChoosed = false;
				that.distAll();
			},
			// 计算选中表格的合计值
			calChoosedSum() {
				const that = this;
				let sum = {
					to: 0, // 分配数
					can: 0, // 规则下可分配数
					can_count: 0, // 总空闲数
					to_exact: 0, // 精准选点数
				};
				let list = that.tableDataChoosed || [];
				list.sort((a, b) => {
					if (a.adcode == b.adcode) {
						if (a.point_type.id == b.point_type.id) {
							return a.id - b.id;
						} else {
							return a.point_type.id - b.point_type.id;
						}
					} else {
						return a.adcode - b.adcode;
					}
				});
				that.tableDataChoosed = list;
				(that.tableDataChoosed || []).forEach(d => {
					sum.to += d.to;
					sum.can += d.can;
					sum.can_count += d.can_count;
					sum.to_exact += (d.to_exact || []).length;
				});
				that.tableDataChoosedSum = sum;

				that.distForm.remain = parseInt(that.distForm.all) - sum.to;
			},
			// 待选列表，显示具体点位
			showExactList(list) {
				const that = this;
				that.exactList = list;
				that.exactVisible = true;
			},
			// 关闭弹窗
			dialogCUClose(formName) {
				const that = this
				switch (formName) {
					case 'exactTable':
						that.exactList = [];
						break;
				}
			},
			// 根据query重置时间段
			resetDateRangeByQuery() {
				const that = this;
				if (that.$route.query.start_at && that.$route.query.end_at) {
					that.searchForm.date_range = [that.$route.query.start_at, that.$route.query.end_at];
				}
			},
			// 获取行业list
			getIndustryList() {
				return list_all3rd_bycode_contrain_del_close({
						code: "khxg-hy"
					})
					.then(res => {
						this.industryList = res.data;
					})
			},
			// 改变商圈选中值
			changeTradeAreaSelect() {
				const that = this;
				const {
					location: {
						lat,
						lng
					}
				} = (that.trade_area_selected || {
					location: {
						lat: null,
						lng: null
					}
				});
				that.searchForm.business_circle.lat = lat;
				that.searchForm.business_circle.lng = lng;
			},
			// 获取公司主营城市
			async getCompanyAdcode() {
				const that = this;
				await that.getPCListAll();
				return get_company_adcode()
					.then(({
						data: {
							adcode,
							lat,
							lng
						}
					}) => {
						let pca = getAdcodeListByAdcode(adcode);
						that.searchForm.pca = pca;
						that.getAreaList(pca[pca.length - 1]);
						that.getTradeAreas(pca[pca.length - 1], lat, lng);
					});
			},
			// 获取商圈列表
			getTradeAreas(adcode, lat, lng) {
				const that = this
				return search_trade_area({
						boundary: adcode,
						lat: lat,
						lng: lng
					})
					.then(({
						data
					}) => {
						that.tradeAreaAll = data
					})
			},
			// 获取pid下所有区
			getAreaList(pid) {
				const that = this
				return area_list({
						pid: pid
					})
					.then(({
						data
					}) => {
						that.areaAll = data
					})
			},
			// 点位类型列表
			getPointTypes() {
				const that = this
				return list_all3rd_bytopcode({
						code: 'dwxg'
					})
					.then(res => {
						const {
							code,
							data
						} = res
						if (code == 200) {
							that.point_types = data
							if ((that.point_types || []).length == 1) {
								that.searchForm.point_type_ids = [that.point_types[0].id];
								that.getPointRules();
							}
							if (!that.point_types_map) that.point_types_map = new Map();
							(that.point_types || []).forEach(p => {
								that.point_types_map.set(parseInt(p.id), p);
							})
						}
					})
			},
			// 改变点位类型
			changePointType() {
				const that = this;
				if ((that.searchForm.point_type_ids || []).length > 0) {
					that.getPointRules();
				} else {
					that.resetPointRule();
					that.tableDataOrigin = [];
					that.handleRule();
					that.filterTableData();
				}
				that.handleTableColShow();
			},
			// 重置规则
			resetPointRule() {
				const that = this;
				that.pointRule = {
					rules: []
				};
			},
			// 获取点位规则
			getPointRules() {
				const that = this;
				that.loadingRules = true;
				get_point_type_dis_rule({
						ids: (that.searchForm.point_type_ids || [])
					})
					.then(({
						data
					}) => {
						if ((data || []).length > 0) {
							data[0].rules.forEach(r => {
								r.on = false;
								r.n = 1;
								r.appoint = [];
							})
						}
						that.pointRule = data[0];
						that.loadingRules = false;
					})
					.catch(() => {
						that.loadingRules = false;
					})
			},
			// 楼盘列表
			getAllBuildings() {
				return get_buildings().then(res => {
					this.buildingAreaList = res.data;
				})
			},
			// 改变规则开关
			changRuleSwitch(val, ruleId) {
				const that = this;
				//const loading = common.showLoading({text: '过滤中'});
				if (val && (ruleId == 4 || ruleId == 5 || ruleId == 6)) {
					(that.pointRule.rules || []).forEach((r, i) => {
						if (r.id == 4 || r.id == 5 || r.id == 6) {
							that.pointRule.rules[i].on = r.id == ruleId;
						}
					});
				}
				that.handleTableColShow();
				that.handleRule();
				//loading.close();
			},
			// 改变规则数量
			changRuleN(val, ruleId) {
				const that = this;
				//const loading = common.showLoading({text: '过滤中'});
				that.handleRule();
				//loading.close();
			},
			// 改变规则指定楼层
			changeRuleAppoint(val, ruleId) {
				const that = this;
				//const loading = common.showLoading({text: '过滤中'});
				(that.pointRule.rules || []).forEach((r, i) => {
					if (r.id == ruleId) {
						that.pointRule.rules[i].on = (val || []).length > 0;
					}
				});

				that.handleRule();
				//loading.close();
			},
			// 处理规则
			handleRule() {
				const that = this;
				that.getCurActiveRule();
				that.filterTableData();
			},
			// 根据规则过滤表格数据
			filterTableData() {
				const that = this;
				//console.log(1);
				const flags = {
					court: that.activeRule.indexOf(1) > -1,
					unit: that.activeRule.indexOf(2) > -1,
					floor: that.activeRule.indexOf(3) > -1,
					a: that.activeRule.indexOf(4) > -1,
					b: that.activeRule.indexOf(5) > -1,
					ab: that.activeRule.indexOf(6) > -1,
					apFloor: that.activeRule.indexOf(7) > -1
				};
				//console.log(2);

				const calCurCanCount = function(flags, data, pid) {
					//console.log(flags);
					let curCanCount = data.can_count;
					data.cur_can_devices = {
						type: 0,
						list: [],
						split: {},
					};
					if (pid == 119) {
						let count = 0;
						if (flags.unit && flags.floor && flags.apFloor) {
							// 同时设置单元数量上限、楼层数量上限、指定楼层
							data.cur_can_devices.type = 2;
							const keys = Object.keys(data.unit_devices) || [];
							const apFloors = (that.pointRuleMap['7'] || {}).appoint || [];
							let out = {};
							keys.forEach(key => {
								out[key] = {
									max: 0,
									list: []
								};
								let floorMap = new Map();
								(data.unit_devices[key] || []).forEach(d => {
									let list = floorMap.get(d.floor) || [];
									list.push(d);
									list = list.filter(d => apFloors.indexOf('' + d.floor) > -1);
									if ((list || []).length > 0) floorMap.set(d.floor, list);
								});
								for (const [floor, list] of floorMap) {
									if ((list || []).length > 0) {
										const inner = {
											floor: '' + floor,
											max: that.pointRuleMap['3'].n,
											list: list
										};
										out[key].list.push(inner);
									}
								}
								out[key].max = Math.min(out[key].list.length, that.pointRuleMap['2'].n);
								if (out[key].max > 0) {
									count += out[key].max;
								} else {
									delete out[key];
								}
							})
							data.cur_can_devices.split = out;
							curCanCount = count;
						} else if (flags.unit && flags.floor) {
							// 同时设置单元数量上限、楼层数量上限
							data.cur_can_devices.type = 2;
							const keys = Object.keys(data.unit_devices) || [];
							let out = {};
							keys.forEach(key => {
								out[key] = {
									max: 0,
									list: []
								};
								let floorMap = new Map();
								(data.unit_devices[key] || []).forEach(d => {
									let list = floorMap.get(d.floor) || [];
									list.push(d);
									floorMap.set(d.floor, list);
								});
								for (const [floor, list] of floorMap) {
									if ((list || []).length > 0) {
										const inner = {
											floor: '' + floor,
											max: that.pointRuleMap['3'].n,
											list: list
										};
										out[key].list.push(inner);
									}
								}
								out[key].max = Math.min(out[key].list.length, that.pointRuleMap['2'].n);
								if (out[key].max > 0) {
									count += out[key].max;
								} else {
									delete out[key];
								}
							})
							data.cur_can_devices.split = out;
							curCanCount = count;
						} else if (flags.unit && flags.apFloor) {
							// 同时设置单元数量上限、指定楼层
							data.cur_can_devices.type = 1;
							const keys = Object.keys(data.unit_devices) || [];
							const apFloors = (that.pointRuleMap['7'] || {}).appoint || [];
							for (const key of keys) {
								data.cur_can_devices.split[key] = {
									max: 0,
									list: []
								};
								let c = 0;
								(data.unit_devices[key] || []).forEach(d => {
									const floor = '' + d.floor;
									if (apFloors.indexOf(floor) > -1) {
										if (c < that.pointRuleMap['2'].n) {
											c++;
										}
										data.cur_can_devices.split[key].list.push(d);
									}
								});
								if (c > 0) {
									data.cur_can_devices.split[key].max = c;
									count += c;
								} else {
									delete data.cur_can_devices.split[key];
								}
							}
							curCanCount = count;
						} else if (flags.floor && flags.apFloor) {
							// 同时设置指定楼层、楼层数量上限
							data.cur_can_devices.type = 1;
							const keys = Object.keys(data.floor_devices) || [];
							const apFloors = (that.pointRuleMap['7'] || {}).appoint || [];
							for (const key of keys) {
								const floor = key.substring(key.lastIndexOf('_') + 1);
								if (apFloors.indexOf(floor) > -1 && (data.floor_devices[key] || []).length >= that
									.pointRuleMap['3'].n) {
									data.cur_can_devices.split[key] = {
										max: that.pointRuleMap['3'].n,
										list: data.floor_devices[key] || []
									};
									count++;
								}
							}
							curCanCount = count;
						} else if (flags.unit) {
							// 仅单元数量限制
							data.cur_can_devices.type = 1;
							const keys = Object.keys(data.unit_devices) || [];
							for (const key of keys) {
								if ((data.unit_devices[key] || []).length >= that.pointRuleMap['2'].n) {
									const max = Math.min((data.unit_devices[key] || []).length, that.pointRuleMap['2']
										.n);
									data.cur_can_devices.split[key] = {
										max: max,
										list: data.unit_devices[key] || []
									};
									count += max;
								}
							}
							curCanCount = count;
						} else if (flags.floor) {
							// 仅楼层数量上限
							data.cur_can_devices.type = 1;
							const keys = Object.keys(data.floor_devices) || [];
							for (const key of keys) {
								if ((data.floor_devices[key] || []).length >= that.pointRuleMap['3'].n) {
									data.cur_can_devices.split[key] = {
										max: that.pointRuleMap['3'].n,
										list: data.floor_devices[key] || []
									};
									count++;
								}
							}
							curCanCount = count;
						} else if (flags.apFloor) {
							// 仅指定楼层
							const keys = Object.keys(data.floor_devices) || [];
							const apFloors = (that.pointRuleMap['7'] || {}).appoint || [];
							for (const key of keys) {
								const floor = key.substring(key.lastIndexOf('_') + 1);
								if (apFloors.indexOf(floor) > -1) {
									data.cur_can_devices.type = 0;
									data.cur_can_devices.list = data.cur_can_devices.list.concat(data.floor_devices[
										key]);
									count++;
								}
							}
							curCanCount = count;
						} else {
							//console.log(123);
							count = data.can_count || 0;
							curCanCount = count;
						}
					}
					if (pid == 120) {
						if (flags.court && flags.a) {
							data.cur_can_devices.type = 0;
							data.cur_can_devices.list = data.a_devices || [];
							curCanCount = Math.min(data.cur_can_devices.list.length, that.pointRuleMap['1'].n);
						} else if (flags.court && flags.b) {
							data.cur_can_devices.type = 0;
							data.cur_can_devices.list = data.b_devices || [];
							curCanCount = Math.min(data.cur_can_devices.list.length, that.pointRuleMap['1'].n);
						} else if (flags.court && flags.ab) {
							data.cur_can_devices.type = 0;
							data.cur_can_devices.list = data.ab_devices || [];
							let c = Math.min(data.cur_can_devices.list.length * 2, that.pointRuleMap['1'].n);
							if (c % 2 == 1) c -= 1;
							curCanCount = c;
						} else if (flags.a) {
							data.cur_can_devices.type = 0;
							data.cur_can_devices.list = data.a_devices || [];
							curCanCount = data.cur_can_devices.list.length;
						} else if (flags.b) {
							data.cur_can_devices.type = 0;
							data.cur_can_devices.list = data.b_devices || [];
							curCanCount = data.cur_can_devices.list.length;
						} else if (flags.ab) {
							data.cur_can_devices.type = 0;
							data.cur_can_devices.list = data.ab_devices || [];
							curCanCount = data.cur_can_devices.list.length * 2;
						} else if (flags.court) {
							data.cur_can_devices.type = 0;
							data.cur_can_devices.list = data.court_devices || [];
							curCanCount = data.cur_can_devices.list.length;
						} else {
							count = data.can_count || 0;
							curCanCount = count;
						}
					}
					data.cur_can_count = (curCanCount <= data.can_count ? curCanCount : data.can_count);
					return data;
				}

				//console.log(3);
				let buildings = [];
				that.tableDataOrigin.map(data => {
					let f = true;
					if (flags.court) {
						if (data.court_count <= 0) {
							f = false;
						} else {
							f = (data.court_devices || []).length >= that.pointRuleMap['1'].n;
						}
					}
					if (flags.unit) {
						if (data.unit_count <= 0) {
							f = false;
						} else {
							let cF = false;
							const keys = Object.keys(data.unit_devices) || [];
							for (const key of keys) {
								cF = cF || ((data.unit_devices[key] || []).length >= that.pointRuleMap['2'].n)
							}
							f = cF;
						}
					}
					if (flags.floor) {
						if (data.floor_count <= 0) {
							f = false;
						} else {
							let cF = false;
							const keys = Object.keys(data.floor_devices) || [];
							for (const key of keys) {
								cF = cF || ((data.floor_devices[key] || []).length >= that.pointRuleMap['3'].n)
							}
							f = cF;
						}
					}
					if (flags.apFloor) {
						if (data.floor_count <= 0) {
							f = false;
						} else {
							f = that.pointRuleMap['7'].on && ((that.pointRuleMap['7'] || {}).appoint || [])
								.length > 0;
						}
					}
					if (flags.a) {
						if (data.a_count <= 0) {
							f = false;
						} else {
							f = (data.a_devices || []).length >= 0;
						}
					}
					if (flags.b) {
						if (data.b_count <= 0) {
							f = false;
						} else {
							f = (data.b_devices || []).length >= 0;
						}
					}
					if (flags.ab) {
						if (data.ab_count <= 0) {
							f = false;
						} else {
							f = (data.ab_devices || []).length >= 0;
						}
					}
					//console.log(f);
					if (f) {
						const point_type_pid = that.point_types_map.get(that.searchForm.point_type_ids[0]).pid;
						data = calCurCanCount(flags, data, point_type_pid);
						//console.log(data);
						if (data.cur_can_count > 0) buildings.push(data);
					}
				})
				that.tableData = buildings;
			},
			// 处理表格列显示
			handleTableColShow() {
				const that = this;
				that.getCurActiveRule();
				const ruleIds = (that.pointRule.rules || []).map(r => parseInt(r.id));
				that.tableColShow.hasCourt = ruleIds.indexOf(1) > -1 && that.activeRule.indexOf(1) > -1;
				that.tableColShow.hasUnit = ruleIds.indexOf(2) > -1 && that.activeRule.indexOf(2) > -1;
				that.tableColShow.hasFloor = ruleIds.indexOf(3) > -1 && that.activeRule.indexOf(3) > -1;
				that.tableColShow.hasA = ruleIds.indexOf(4) > -1 && that.activeRule.indexOf(4) > -1;
				that.tableColShow.hasB = ruleIds.indexOf(5) > -1 && that.activeRule.indexOf(5) > -1;
				that.tableColShow.hasAB = ruleIds.indexOf(6) > -1 && that.activeRule.indexOf(6) > -1;
			},
			// 当前启用的分配规则
			getCurActiveRule() {
				const that = this;
				that.activeRule = [];
				(that.pointRule.rules || []).forEach(r => {
					if (r.on) {
						that.activeRule.push(r.id);
						that.pointRuleMap['' + r.id] = r;
					}
				});

			},
			// 列表
			getList() {
				const that = this;
				that.tabLoading = true;
				let date_range = {
					start_at: that.listParams.date_range[0] || null,
					end_at: that.listParams.date_range[1] || null
				};
				get_choose_data(Object.assign({}, that.listParams, {
						date_range: date_range
					}))
					.then(({
						data
					}) => {
						that.tabLoading = false;
						let buildings = [];
						const point_type_id = '' + that.searchForm.point_type_ids[0];
						that.getCurActiveRule();
						(data.buildings || []).forEach(b => {
							const counts = b.counts[point_type_id][0];
							b.devices[point_type_id] = b.devices[point_type_id] || [];
							const devices = b.devices[point_type_id];
							b.can_count = counts.available_num + counts.movable_num;
							b.used_count = counts.used_num;
							b.lock_count = counts.locked_num;
							b.all_count = counts.available_num + counts.movable_num + counts.used_num + counts
								.locked_num;
							let unitSet = new Set(),
								floorSet = new Set();
							let courtCount = 0,
								unitCount = 0,
								floorCount = 0,
								aCount = 0,
								bCount = 0,
								abCount = 0;
							let court_devices = [],
								unit_devices = {},
								floor_devices = {},
								a_devices = [],
								b_devices = [],
								ab_devices = [];
							devices.sort((a, b) => {
								if (a.point_type_pid == 119) {
									if (a.building_number == b.building_number) {
										if (a.unit_number == b.unit_number) {
											if (a.floor == b.floor) {
												return a.code - b.code;
											} else {
												return a.floor - b.floor;
											}
										} else {
											return a.unit_number - b.unit_number;
										}
									} else {
										return a.building_number - b.building_number;
									}
								}
								if (a.point_type_pid == 120) {
									if (a.door_number == b.door_number) {
										return a.code - b.code;
									} else {
										return a.door_number - b.door_number;
									}
								}
								if (a.point_type_pid == 120) {
									return a.code - b.code;
								}
							});
							devices.forEach(d => {
								courtCount++;
								court_devices.push(cloneDeep(d));
								if (d.media_feature === 'A面') {
									aCount++;
									a_devices.push(cloneDeep(d));
								}
								if (d.media_feature === 'B面') {
									bCount++;
									b_devices.push(cloneDeep(d));
								}
								if ('' + d.point_type_pid == '119') {
									if (d.unit_number) {
										unitSet.add(d.building_number + '_' + d.unit_number);
										let ds = unit_devices[d.building_number + '_' + d
											.unit_number] || [];
										ds.push(cloneDeep(d));
										unit_devices[d.building_number + '_' + d.unit_number] = ds
									}
									if (d.floor) {
										floorSet.add(d.building_number + '_' + d.unit_number + '_' + d
											.floor);
										let ds = floor_devices[d.building_number + '_' + d
											.unit_number + '_' + d.floor] || [];
										ds.push(cloneDeep(d));
										floor_devices[d.building_number + '_' + d.unit_number + '_' + d
											.floor] = ds
									}
								}
							});
							unitCount = unitSet.size;
							floorCount = floorSet.size;
							if (aCount > 0 && bCount > 0) {
								let aSet = new Set(),
									bSet = new Set();
								let aMap = new Map(),
									bMap = new Map();
								a_devices.forEach(d => {
									const key = d.building_area_id + '_' + d.door_number + '_' + (d
										.rail_number || '');
									aSet.add(key);
									aMap.set(key, d);
								});
								b_devices.forEach(d => {
									const key = d.building_area_id + '_' + d.door_number + '_' + (d
										.rail_number || '');
									bSet.add(key);
									bMap.set(key, d);
								});
								aSet.forEach(key => {
									if (bSet.has(key)) {
										abCount++;
										ab_devices.push({
											a: aMap.get(key),
											b: bMap.get(key)
										});
									}
								});
							}
							b.court_count = courtCount;
							b.court_devices = court_devices;
							b.unit_count = unitCount;
							b.unit_devices = unit_devices;
							b.floor_count = floorCount;
							b.floor_devices = floor_devices;
							b.a_count = aCount;
							b.a_devices = a_devices;
							b.b_count = bCount;
							b.b_devices = b_devices;
							b.ab_count = abCount;
							b.ab_devices = ab_devices;

							buildings.push(b);
						});
						let list = JSON.parse(JSON.stringify(buildings || []));
						list.sort((a, b) => {
							if (a.adcode == b.adcode) {
								return a.id - b.id;
							} else {
								return a.adcode - b.adcode;
							}
						});
						that.tableDataOrigin = list;
						that.filterTableData();
					})
					.catch(() => {
						that.tabLoading = false;
					})
			},
			// 合计行方法
			getChoosedSummaries(param) {
				const that = this;
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '合计';
						return;
					} else if (index === 5) {
						sums[index] = that.tableDataChoosedSum.can_count;
						return;
					} else if (index === 6) {
						sums[index] = that.tableDataChoosedSum.can;
						return;
					} else if (index === 7) {
						sums[index] = that.tableDataChoosedSum.to;
						return;
					} else if (index === 8) {
						sums[index] = that.tableDataChoosedSum.to_exact;
						return;
					} else {
						sums[index] = '';
						return;
					}
				});

				return sums;
			},
			// 重置搜索表单
			resetSearchForm() {
				this.trade_area_selected = [];
				this.searchForm = Object.assign(this.searchForm, {
					point_type_ids: [],
					date_range: [formatDate(new Date()) + ' 00:00:00', formatDate(new Date()) + ' 23:59:59'],
					building_area_ids: [],
					address: null,
					address_circle: {
						lng: null,
						lat: null,
						radius: 1000
					},
					business_circle: {
						lat: null,
						lng: null,
						radius: 1000
					},
					industry_id: null,
					price_range: {
						min: null,
						max: null
					}
				})
			},
			// 重置搜索表单
			searchReset() {
				this.$refs.searchForm.resetFields();
				this.resetSearchForm();
				const params = this.$refs.searchForm.model
				this.listParams = Object.assign(this.listParams, this.searchForm)
				if ((this.point_types || []).length == 1) {
					this.searchForm.point_type_ids = [this.point_types[0].id];
					this.getPointRules();
				} else {
					this.resetPointRule();
				}
				this.getList()
			},
			// 搜索
			searchSubmit(formName) {
				this.$refs[formName].validate(valid => {
					if (valid) {
						const params = this.$refs[formName].model
						this.listParams = Object.assign(this.listParams, params)
						this.getList()
					} else {
						console.log('error submit!!')
						return false
					}
				})
			},
		}
	}
</script>
<style>
	.search .el-form-item:last-child {
		margin-left: 35px;
	}

	.el-date-editor>.el-range-separator {
		width: 8% !important;
	}

	.operation button {
		padding: 8px;
	}

	.el-pagination {
		margin-top: 40px;
	}
</style>
<style lang="scss" scoped>
	.app-container {
		/deep/.el-table {
			margin-top: 20px;

			.names-tag {
				box-sizing: border-box;
				margin: 3px;
			}

			.stop-row {
				color: #bbb !important;
			}

			&.el-table--scrollable-x .el-table__body-wrapper {
				z-index: 1 !important;
			}
		}
	}
</style>
